package cn.qidisoft.edu.hzjt.controller.zyc;

import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.common.pagination.Page;
import cn.qidisoft.core.common.pagination.PaginationBean;
import cn.qidisoft.core.util.moffice.excel.ErrorMessageBean;
import cn.qidisoft.core.util.moffice.excel.ExcelUtil;
import cn.qidisoft.core.util.moffice.excel.ExpExcelUtil;
import cn.qidisoft.core.util.moffice.excel.ImportMsgHelper;
import cn.qidisoft.core.web.customargument.bind.annotation.IfNeedLogin;
import cn.qidisoft.core.web.customargument.bind.annotation.Token;
import cn.qidisoft.edu.hzjt.annotation.SysLogger;
import cn.qidisoft.edu.hzjt.constants.Constant;
import cn.qidisoft.edu.hzjt.controller.BaseController;
import cn.qidisoft.edu.hzjt.exception.RPCException;
import cn.qidisoft.edu.hzjt.model.ResponseResult;
import cn.qidisoft.edu.hzjt.model.UserEmployee;
import cn.qidisoft.edu.hzjt.model.zyc.PartyBranch;
import cn.qidisoft.edu.hzjt.model.zyc.PartyLeagueMember;
import cn.qidisoft.edu.hzjt.model.zyc.PartyMembershipDues;
import cn.qidisoft.edu.hzjt.service.zyc.IDfService;
import cn.qidisoft.edu.hzjt.service.zyc.IDyService;
import cn.qidisoft.edu.hzjt.service.zyc.IDzbService;
import cn.qidisoft.edu.hzjt.utils.LogType;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 党费管理
 * 
 * @author zhangwenliang
 * @date 2018.11.16
 */
@Controller
@RequestMapping(value = "/df/")
@IfNeedLogin(needLogin = true)
public class DfController {
	protected static final LoggerAdapter LOGGER = LoggerAdapterFactory.getLogger(LogType.HZJT_LOGGER.val);
	@Autowired
	private IDyService dyService;

	@Autowired
	private IDfService dfService;

	@Autowired
	private IDzbService dzbService;

	/**
	 * 跳转到党费管理列表页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "list")
	public String list(ModelMap model, HttpServletRequest request) {
		// 获取党支部信息
		PartyBranch  partyBranch = new PartyBranch();
		List<PartyBranch> pList = (List<PartyBranch>) dzbService.getAllDzbinfo(partyBranch);
		request.setAttribute("pList", pList);
		return "zyc/df/list";
	}

	/**
	 * 获取列表分页数据
	 * 
	 * @param model
	 * @param request
	 * @param pageSize
	 * @param currentPage
	 * @param partyBranch
	 * @return
	 */
	@RequestMapping("getListData")
	@ResponseBody
	public ResponseResult getListData(ModelMap model, HttpServletRequest request,
			@RequestParam(value = "rows", required = false) String pageSize,
			@RequestParam(value = "page", required = false) String currentPage,
			PartyMembershipDues PartyMembershipDues) {
		Page page = new Page();
		page.setCurrPage(currentPage == null ? 0 : Integer.valueOf(currentPage));
		page.setPageSize(pageSize == null ? 10 : Integer.valueOf(pageSize));
		BaseController.setSortByColumn(request, "createTime", "asc");
		PartyMembershipDues.setOrderField((String) request.getAttribute("orderField"));
		PartyMembershipDues.setOrderFlag((String) request.getAttribute("orderFlag"));
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("dZBID", request.getParameter("dZBID"));
		queryMap.put("dYLB", request.getParameter("dYLB"));
		queryMap.put("dJZT", request.getParameter("dJZT"));
		queryMap.put("xB", request.getParameter("xB"));
		queryMap.put("mZ", request.getParameter("mZ"));
		queryMap.put("wHCD", request.getParameter("wHCD"));
		queryMap.put("isStu", request.getParameter("isStu"));
		if(request.getParameter("xM") != null) {
			queryMap.put("xM", request.getParameter("xM").trim());			
		}else {
			queryMap.put("xM", request.getParameter("xM"));
		}queryMap.put("PartyMembershipDues", PartyMembershipDues);
		PaginationBean<PartyMembershipDues> paginationBean = dfService.getListData(queryMap, page);
		ResponseResult result = new ResponseResult();
		result.setTotal(paginationBean.getTotalRecords());
		result.setRows(paginationBean.getPageList());
		return result;
	}
	/**
	 * 跳转到添加页面
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "add")
	@Token(save = true)
	public String add(ModelMap model, HttpServletRequest request) {
		try {
			// 获取党员信息(党籍状态为正常1)
			Map<String, Object> queryMap = new HashMap<String,Object>();
			PartyLeagueMember partyLeagueMember = new PartyLeagueMember();
			partyLeagueMember.setdJZT("1");
			queryMap.put("PartyLeagueMember", partyLeagueMember);
			List<PartyLeagueMember> partyLeagueMembers = dyService.getDybList(queryMap);
			request.setAttribute("partyLeagueMember", partyLeagueMembers);
			return "zyc/df/add";
		} catch (Exception e) {
			LOGGER.error("获得xxxxx信息 addStudentDemoForward [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
	}

	/**
	 * 添加党费信息
	 * 
	 * @param model
	 * @param request
	 * @param pM
	 * @return
	 */
	@RequestMapping(value = "insert", method = RequestMethod.POST)
	public String insert(ModelMap model, HttpServletRequest request, PartyMembershipDues pM) {
		try {
			// 得到登陆人的信息
			UserEmployee userEmployee = (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
			pM.setgID("1");
			pM.setCreatorId(userEmployee.getEmid());
			pM.setCreatorName(userEmployee.getXm());
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String formatStr =formatter.format(new Date());
			// new Date()为获取当前系统时间
			pM.setCreateTime(formatStr);
			if(null == pM.getdFJE()) {
				pM.setdFJE(0.0);
			}
			// 插入党费信息
			dfService.insertDfInfo(pM);
			// 根据党员id获取党员信息
			PartyLeagueMember partyLeagueMember = dyService.getDybById(pM.getdYID());
			
			request.setAttribute("partyLeagueMember", partyLeagueMember);
			request.setAttribute("partyMembershipDues", pM);
			String action = request.getParameter("action");
			if (action.equals("1")) {
				return "redirect:./view?dFID="+pM.getdFID();
			} else if (action.equals("2")) {
				return "redirect:./add";
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("获得xxxxx信息 addStudentDemo [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
		return null;
	}
	
	@RequestMapping("view")
	public String view(HttpServletRequest request) {
		String dFID = request.getParameter("dFID");
		// 获取党费信息
		PartyMembershipDues partyMembershipDues =  dfService.getById(Integer.parseInt(dFID));
		// 获取党员信息(根据党员部id)
		PartyLeagueMember pLeagueMember = dyService.getDybById(partyMembershipDues.getPartyLeagueMember().getdYID());
		if(null !=pLeagueMember.getcSRQ()) {
			pLeagueMember.setcSRQ(pLeagueMember.getcSRQ().substring(0, 19));
		}
		if(null !=pLeagueMember.getrDRQ()) {
			pLeagueMember.setrDRQ(pLeagueMember.getrDRQ().substring(0, 19));
		}
		if(null !=pLeagueMember.getzZRQ()) {
			pLeagueMember.setzZRQ(pLeagueMember.getzZRQ().substring(0, 19));
		}
		if(pLeagueMember.getdYLB().equals("1")) {
			pLeagueMember.setdYLB("正式党员");
		} else if(pLeagueMember.getdYLB().equals("2")) {
			pLeagueMember.setdYLB("预备党员");
		}
		if(pLeagueMember.getdJZT().equals("1")) {
			pLeagueMember.setdJZT("正常");
		} else if(pLeagueMember.getdJZT().equals("0")) {
			pLeagueMember.setdJZT("停止党籍");
		}
		if(pLeagueMember.getIsStu().equals("0")) {
			pLeagueMember.setIsStu("否");
		} else {
			pLeagueMember.setIsStu("是");
		}
		request.setAttribute("partyLeagueMember", pLeagueMember);
		request.setAttribute("partyMembershipDues", partyMembershipDues);
		return "zyc/df/view";
	}

	/**
	 * 跳转到修改页面
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "edit")
	public String edit(ModelMap model, HttpServletRequest request) {
		try {
			String dFID = request.getParameter("dFID");
			String dYID = request.getParameter("dYID");
			// 获取党费信息
			PartyMembershipDues partyMembershipDues =  dfService.getById(Integer.parseInt(dFID));
			// 获取党员信息(根据党员部id)
			PartyLeagueMember pLeagueMember = dyService.getDybById(partyMembershipDues.getPartyLeagueMember().getdYID());
			if(null !=pLeagueMember.getcSRQ()) {
				pLeagueMember.setcSRQ(pLeagueMember.getcSRQ().substring(0, 19));
			}
			if(null !=pLeagueMember.getrDRQ()) {
				pLeagueMember.setrDRQ(pLeagueMember.getrDRQ().substring(0, 19));
			}
			if(null !=pLeagueMember.getzZRQ()) {
				pLeagueMember.setzZRQ(pLeagueMember.getzZRQ().substring(0, 19));
			}
			if(pLeagueMember.getdYLB().equals("1")) {
				pLeagueMember.setdYLB("正式党员");
			} else if(pLeagueMember.getdYLB().equals("2")) {
				pLeagueMember.setdYLB("预备党员");
			}
			if(pLeagueMember.getdJZT().equals("1")) {
				pLeagueMember.setdJZT("正常");
			} else if(pLeagueMember.getdJZT().equals("0")) {
				pLeagueMember.setdJZT("停止党籍");
			}
			if(pLeagueMember.getIsStu().equals("0")) {
				pLeagueMember.setIsStu("否");
			} else {
				pLeagueMember.setIsStu("是");
			}
			request.setAttribute("partyLeagueMember", pLeagueMember);
			request.setAttribute("partyMembershipDues", partyMembershipDues);
			return "zyc/df/edit";
		} catch (Exception e) {
			LOGGER.error("获得xxxxx信息 addStudentDemoForward [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
	}

	/**
	 * 更新党费信息
	 * 
	 * @param model
	 * @param request
	 * @return 
	 */
	@RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(HttpServletRequest request, PartyMembershipDues pM) {
		try {
			
			UserEmployee userEmployee = (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
			pM.setgID("1");
			pM.setCreatorId(userEmployee.getEmid());
			pM.setCreatorName(userEmployee.getXm());
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String formatStr =formatter.format(new Date());
			// new Date()为获取当前系统时间
			pM.setCreateTime(formatStr);
			// 更新党员表
			if (dfService.updateDfinfo(pM) > 0) {
				String action = request.getParameter("action");
				// 根据党员id获取党员信息
				PartyLeagueMember partyLeagueMember = dyService.getDybById(pM.getdYID());
				request.setAttribute("partyLeagueMember", partyLeagueMember);
				request.setAttribute("partyMembershipDues", pM);
				if (action.equals("1")) {
					return "zyc/df/view";
				} else if (action.equals("2")) {
					return "redirect:./add";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("获得xxxxx信息 addStudentDemo [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
			return "error/error";
		}
		return null;
	}

	/**
	 * 删除党员信息
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	public String delete(ModelMap model, HttpServletRequest request) {
		try {
			String[] idList = request.getParameter("idList").split(",");
			List<Integer> list = new ArrayList<>();
			for (int i = 0; i < idList.length; i++) {
				list.add((Integer.valueOf(idList[i])));

			}
			if (list.size() != 0) {
				dfService.delete(list);
			}
			BaseController.setParameter("msg", "删除成功");
			return "redirect:list";
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("删除 delete [{}] error," + this.getClass().getName() + "=[{}]", this.getClass().getName(),
					e.getMessage());
			return "error/error";
		}
	}

	/**
	 * xxxxx下载
	 * 
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "export_df")
	public @ResponseBody void export_dzb(HttpServletRequest request, HttpServletResponse response,
			PartyMembershipDues pDues) throws Exception {
		try {
			Map<String, Object> queryMap = new HashMap<String, Object>();
			queryMap.put("dZBID", request.getParameter("dZBID"));
			queryMap.put("dYLB", request.getParameter("dYLB"));
			queryMap.put("dJZT", request.getParameter("dJZT"));
			queryMap.put("xB", request.getParameter("xB"));
			queryMap.put("mZ", request.getParameter("mZ"));
			queryMap.put("wHCD", request.getParameter("wHCD"));
			queryMap.put("isStu", request.getParameter("isStu"));
			if(request.getParameter("xM") != null) {
				queryMap.put("xM", request.getParameter("xM").trim());			
			}else {
				queryMap.put("xM", request.getParameter("xM"));
			}
			List<PartyMembershipDues> datalist = dfService.getDfList(queryMap);
			String[][] title_name = { { "党费Id", "姓名", "性别","工号", "身份证号","所在党支部", "党员类别", "学生党员", "年份", "月份", "党费" } };
			String[] title_style = { "hwzs_16_bold_25", "hwzs_16_bold_25", "hwzs_16_bold_25",
					 "hwzs_16_bold_25", "hwzs_16_bold_25", "kt_12_bold_18", "kt_12_bold_18",
					"kt_12_bold_18", "st_12_r_20", "st_12_r_20", "st_12_r_20"};
			String fileName = "党费信息";
			String[] remark = { "" };
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			if (datalist != null && !datalist.isEmpty()) {
				for (PartyMembershipDues res : datalist) {
					Map<String, Object> map = new LinkedHashMap<String, Object>();
					if(null !=res.getPartyLeagueMember().getcSRQ()) {
						res.getPartyLeagueMember().setcSRQ(res.getPartyLeagueMember().getcSRQ().substring(0, 19));
					}
					if(null !=res.getPartyLeagueMember().getrDRQ()) {
						res.getPartyLeagueMember().setrDRQ(res.getPartyLeagueMember().getrDRQ().substring(0, 19));
					}
					if(null !=res.getPartyLeagueMember().getzZRQ()) {
						res.getPartyLeagueMember().setzZRQ(res.getPartyLeagueMember().getzZRQ().substring(0, 19));
					}
					if(res.getPartyLeagueMember().getdYLB().equals("1")) {
						res.getPartyLeagueMember().setdYLB("正式党员");
					} else if(res.getPartyLeagueMember().getdYLB().equals("2")) {
						res.getPartyLeagueMember().setdYLB("预备党员");
					}
					if(res.getPartyLeagueMember().getIsStu().equals("0")) {
						res.getPartyLeagueMember().setIsStu("否");
					} else {
						res.getPartyLeagueMember().setIsStu("是");
					}
					map.put("dFID", res.getdFID());
					map.put("xM", res.getPartyLeagueMember().getxM());
					map.put("xB", res.getPartyLeagueMember().getxB());
					map.put("gH", res.getPartyLeagueMember().getdYID());
					map.put("sFZH", res.getPartyLeagueMember().getsFZH());
					map.put("dZBMC", res.getPartyLeagueMember().getPartyBranch().getdZBMC());
					map.put("dYLB", res.getPartyLeagueMember().getdYLB());
					map.put("isStu", res.getPartyLeagueMember().getIsStu());
					map.put("dFNF", res.getdFNF());
					map.put("dFYF", res.getdFYF());
					map.put("dFJE", res.getdFJE());
					list.add(map);
				}
			}
			HSSFWorkbook wb = ExpExcelUtil.getWorkBookExcel(title_name, title_style, 100, remark, fileName, list);
			try {
				String filenameConvert = "党费信息";/* new String(fileName.getBytes("GB2312"), "ISO8859-1"); */
				response.reset();
				response.setContentType("application/vnd.ms-excel;charset=utf-8");
				response.setHeader("Content-Disposition",
						"attachment;filename=" + new String((filenameConvert + ".xls").getBytes(), "iso-8859-1"));
				response.setDateHeader("Expires", 0);
				ServletOutputStream os = response.getOutputStream();
				wb.write(os);
				os.flush();
			} catch (Exception e) {
				System.out.println("网络连接断开，可能用户取消了导出");
			}
		} catch (RPCException e) {
			LOGGER.error("获得xxxxx信息 exportStudentjobList [{}] error," + this.getClass().getName() + "=[{}]",
					this.getClass().getName(), e.getMessage());
		}
	}
     
	/**
	 *根据党员id自动获取党员信息
	 * @param binder
	 */
	@RequestMapping("getDyinfo")
	@ResponseBody
	public PartyLeagueMember getDyById(@RequestParam("dyid") String dYID) {
		PartyLeagueMember partyLeagueMember = dyService.getDybById(Integer.parseInt(dYID));
		if(null !=partyLeagueMember.getcSRQ()) {
			partyLeagueMember.setcSRQ(partyLeagueMember.getcSRQ().substring(0, 19));
		}
		return partyLeagueMember;
	}
	
	 /**
	   * 
	   * 党费导入功能信息
	   * 
	   * @param multipartFile
	   * @param model
	   * @param request
	   * @param response
	   * @return
	   */
	  @RequestMapping(value = "import_df", method = RequestMethod.POST)
	  @SysLogger(description = "党费信息导入", moduleName = "党费管理", method = "")
	  public String importStudentDemo(MultipartFile multipartFile, ModelMap model,
	      HttpServletRequest request, HttpServletResponse response) {
	    UserEmployee userResp =
	        (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
	    List<ErrorMessageBean> errorList = new ArrayList<ErrorMessageBean>(); // 创建错误集合对象
	    try {
	      // MultipartFile file = practiceMasterForm.getFormfile();
	      if (multipartFile != null) {
	        String name = multipartFile.getOriginalFilename();// 获取上传文件名,包括路径
	        InputStream in = multipartFile.getInputStream(); // 获取文件对象
	        HSSFWorkbook wb = null; // 创建工作簿
	        HSSFSheet sheet = null; // 创建工作sheet
	        try {
	          wb = ExcelUtil.getWorkbook(in); // 检查Excel格式和路径是否有效
	          sheet = ExcelUtil.getFirstSheet(wb);
	          if (sheet == null) {
	            ImportMsgHelper.addErrorList(errorList, "sys-error", ImportMsgHelper.msg_validate_1001);
	            // return errorList;
	          } else {
	            String[] header = ExcelUtil.getFirstSheetRow(sheet); // 得到excel表头
	            int totalRows = sheet.getPhysicalNumberOfRows(); // totalRows是总行数
	            long startTime = System.nanoTime();
	            String exportFlag = request.getParameter("exportFlag");
	            errorList = dfService.importDfInfo(errorList, wb, sheet, header,
	                totalRows, in, Integer.parseInt(exportFlag));
	            long estimatedTime = (long) ((System.nanoTime() - startTime) * 0.000000001);
	            if (errorList.size() > 0 && totalRows <= 1) {
	              model.addAttribute("flag", Constant.ALL_FAIL);// 失败
	            } else if (errorList.size() > 0 && errorList.size() < totalRows - 1) {
	              model.addAttribute("flag", Constant.PART_SUCESS);// 部分成功
	            } else if (errorList.size() == 0) {
	              model.addAttribute("flag", Constant.All_SUCESS);// 全部成功
	            } else if (errorList.size() == totalRows - 1) {
	              model.addAttribute("flag", Constant.ALL_FAIL);// 失败
	            }
	            model.addAttribute("estimatedTime", estimatedTime);
	            model.addAttribute("Count", totalRows - 1);
	            model.addAttribute("sucessCout", totalRows - errorList.size() - 1);
	            model.addAttribute("failCout", errorList.size());
	          }
	        } catch (Exception e) {
	          ImportMsgHelper.addErrorList(errorList, "sys-error", ImportMsgHelper.msg_validate_0001);
	          e.printStackTrace();
	          // return errorList;
	        }
	      }
	      model.addAttribute("errorList", errorList);
	      model.addAttribute("now", new Date());
	      model.addAttribute("project", "党费信息导入");
	      model.addAttribute("backUrl", "df/list");
	    } catch (Exception e) {
	      e.printStackTrace();
	      LOGGER.error("获得xxxxx信息 import_df [{}] error," + this.getClass().getName() + "=[{}]",
	          this.getClass().getName(), e.getMessage());
	      return "error/error";
	    }
	    return "import_message";
	  }
	
	
	/**
	 * 处理时间格式
	 * @param binder
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}
}
